package com.hams.demo.system.entity.dto;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import com.hams.demo.common.util.Sex;
import com.hams.demo.system.entity.User;


public class UserQueryDTO {
	
		private String userName;
		private String password;
		private Sex sex;
		private String telePhone;
			
		public Sex getSex() {
			return sex;
		}
		public String getTelePhone() {
			return telePhone;
		}
	
		public String getUserName() {
			return userName;
		}
		public void setUserName(String userName) {
			this.userName = userName;
		}
		public String getPassword() {
			return password;
		}
		public void setPassword(String password) {
			this.password = password;
		}
		public void setTelePhone(String telePhone) {
			this.telePhone = telePhone;
		}
		public void setSex(Sex sex) {
			this.sex = sex;
		}
		//提供static的工具方法：根据当前 userQueryDTO 对象来组装动态查询条件
		public static Specification<User> getSpecification(UserQueryDTO userQueryDTO)
		{
			Specification<User> spec = new Specification<User>() {
				public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
					//1.Predicate查询条件集合
					 List<Predicate> list = new ArrayList<Predicate>(); 
					 
					//2.根据 QueryDTO数据字段的值进行判断以及条件的组装
					 if(null != userQueryDTO && !StringUtils.isEmpty(userQueryDTO.getUserName())) {
						 Predicate  p1 =  cb.like(root.get("userName").as(String.class),"%"+ userQueryDTO.getUserName() + "%");
						 list.add(p1);
					 }
					 if(null != userQueryDTO && !StringUtils.isEmpty(userQueryDTO.getPassword())) {
						 Predicate  p2 =  cb.like(root.get("password").as(String.class),"%"+ userQueryDTO.getPassword() + "%");
						 list.add(p2);
					 }
					 if(null != userQueryDTO && !StringUtils.isEmpty(userQueryDTO.getSex())) {
						 Predicate  p3 =  cb.like(root.get("sex").as(String.class),"%"+ userQueryDTO.getSex() + "%");
						 list.add(p3);
					 }
					 if(null != userQueryDTO && !StringUtils.isEmpty(userQueryDTO.getTelePhone())) {
						 Predicate  p4 =  cb.like(root.get("telePhone").as(String.class),"%"+ userQueryDTO.getTelePhone() + "%");
						 list.add(p4);
					 }
					 //3.Predicate查询条件集合的 size 创建对应的Predicate查询条件数组
					 Predicate[] p = new Predicate[list.size()];  
					 //4.CriteriaBuilder的and 函数组装 查询条件数组
					 return cb.and(list.toArray(p));  
				}
			};
			return spec;
		}
		
	}

